package com.jcli._定时提醒;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TimerApp {
    // private static final int TIMER_DELAY = 20 * 60 * 1000; // 20 minutes in milliseconds
    private static final int TIMER_DELAY = 6000; // 20 minutes in milliseconds

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Timer App");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton startButton = new JButton("Start Timer");
        startButton.addActionListener(e -> startTimer());

        frame.getContentPane().add(startButton, BorderLayout.CENTER);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void startTimer() {
        Timer timer = new Timer(TIMER_DELAY, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showNotification();
            }
        });

        timer.setRepeats(false); // Set to false to run only once  设置为false仅运行一次
        timer.start();
    }

    private static void showNotification() {
        if (SystemTray.isSupported()) {
            try {
                SystemTray tray = SystemTray.getSystemTray();

                // Load an image for the tray icon (adjust the path accordingly)
                //加载托盘图标的图像（相应地调整路径）
                Image image = Toolkit.getDefaultToolkit().getImage("path/to/icon.png");

                // Create a popup menu
                // 创建弹出菜单
                PopupMenu popupMenu = new PopupMenu();
                MenuItem exitItem = new MenuItem("Exit");
                exitItem.addActionListener(e -> System.exit(0));
                popupMenu.add(exitItem);

                // Create the tray icon  创建托盘图标
                TrayIcon trayIcon = new TrayIcon(image, "Timer Notification", popupMenu);
                trayIcon.setImageAutoSize(true);

                // Add the tray icon to the system tray 将托盘图标添加到系统托盘
                tray.add(trayIcon);

                // Display a message in the notification  在通知中显示消息
                trayIcon.displayMessage("Time's up!", "It's time to take a break.", TrayIcon.MessageType.INFO);
            } catch (AWTException ex) {
                ex.printStackTrace();
            }
        } else {
            System.out.println("SystemTray is not supported");
        }
    }
}
